﻿using Dapper;
using ERPEF.Model;
using ERPService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Data;

namespace S4Project.Controllers
{
    [Route("api/[controller]/[action]")]
    [Consumes("application/json")]
    [ApiController]
    public class PurSalesReturnController : ControllerBase
    {
        private readonly MyDbContext myDbContext;
        private readonly pur_Sales_ReturnService _ReturnService;
        public PurSalesReturnController(MyDbContext myDbContext, pur_Sales_ReturnService pur_Sales_ReturnService)
        {
            this.myDbContext = myDbContext;
            this._ReturnService = pur_Sales_ReturnService;
        }
        
        //采购退货查询
        [HttpGet]
        public ActionResult<FenYe<pur_Sales_Return>> SalesRetFenYe(int currentPage, int pageSize, string where)
        {
            using (var conn = myDbContext.Database.GetDbConnection())
            {
                conn.Open();
                var parameters = new DynamicParameters();
                parameters.Add("pageSize", dbType: DbType.Int32, direction: ParameterDirection.Input, value: pageSize);
                parameters.Add("keyName", dbType: DbType.String, direction: ParameterDirection.Input, value: "Return_Id"); // 更改为正确的列名
                parameters.Add("tableName", dbType: DbType.String, direction: ParameterDirection.Input, value: "pur_Sales_Return"); // 更改为正确的表名
                parameters.Add("currentPage", dbType: DbType.Int32, direction: ParameterDirection.Input, value: currentPage);
                parameters.Add("where", dbType: DbType.String, direction: ParameterDirection.Input, value: where); // 添加 where 参数
                parameters.Add("row", dbType: DbType.Int32, direction: ParameterDirection.Output); // 修改为和存储过程中一致的参数名
                string sql = "[dbo].[FenYe]";
                var result = conn.Query<pur_Sales_Return>(sql, parameters, commandType: CommandType.StoredProcedure);
                int row = parameters.Get<int>("row");
                FenYe<pur_Sales_Return> fenye = new FenYe<pur_Sales_Return>()
                {
                    SalesRtourn = result,
                    Rows = row,
                };

                if (fenye.SalesRtourn.Any())
                {
                    return fenye;
                }
                else
                {
                    return Content("没有查到数据");
                }
            }
        }

        [HttpGet]
        public ActionResult<FenYe<pur_Sales_From>> getFenYeC(int currentPage, int pageSize, string where)
        {
            using (var conn = myDbContext.Database.GetDbConnection())
            {
                conn.Open();
                var parameters = new DynamicParameters();
                parameters.Add("pageSize", dbType: DbType.Int32, direction: ParameterDirection.Input, value: pageSize);
                parameters.Add("keyName", dbType: DbType.String, direction: ParameterDirection.Input, value: "Return_Id"); // 更改为正确的列名
                parameters.Add("tableName", dbType: DbType.String, direction: ParameterDirection.Input, value: "pur_Sales_From"); // 更改为正确的表名
                parameters.Add("currentPage", dbType: DbType.Int32, direction: ParameterDirection.Input, value: currentPage);
                parameters.Add("where", dbType: DbType.String, direction: ParameterDirection.Input, value: where); // 添加 where 参数
                parameters.Add("row", dbType: DbType.Int32, direction: ParameterDirection.Output); // 修改为和存储过程中一致的参数名
                string sql = "[dbo].[FenYe]";
                var result = conn.Query<pur_Sales_From>(sql, parameters, commandType: CommandType.StoredProcedure);
                int row = parameters.Get<int>("row");
                FenYe<pur_Sales_From> fenYe = new FenYe<pur_Sales_From>()
                {
                    SalesFrom = result,
                    Rows = row,
                };
                if (fenYe.SalesFrom.Any())
                {
                    return fenYe;
                }
                else
                {
                    return Content("没有查到数据");
                }
            }
        }

        

        /// <summary>
        /// 添加退货信息
        /// </summary>
        /// <param name="AddReturn"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AddReturn([FromBody] pur_Sales_Return sales_Return)
        {
            // 查询当前最大编码
            int maxCodeNumber = int.Parse(await GetMaxCodeNumber());

            // 生成新编码
            string newCode = GenerateSaleCode(maxCodeNumber);

            sales_Return.Return_code = newCode;

            if (ModelState.IsValid)
            {

                int result = await _ReturnService.ReturnAdd(sales_Return);
                if (result > 0)
                {
                    // 查询对应的销售订单
                    var salesOrder = await _ReturnService.GetByCode(sales_Return.ord_number);

                    var salesOut = await _ReturnService.GetByOutCode(sales_Return.ord_number);

                    if (salesOrder != null)
                    {
                        // 如果找到对应的销售订单，则更新其退货状态为 "1"
                        salesOrder.so_Return_status = "1";
                        await _ReturnService.Update(salesOrder);

                        var saleOut = await myDbContext.pur_Chase_Receipt.FirstOrDefaultAsync(so => so.pr_number == salesOrder.ord_number);
                        if (saleOut != null)
                        {
                            saleOut.out_Return_status = salesOrder.so_Return_status;
                        }
                    }
                    else
                    {
                        salesOut.out_Return_status = "1";
                        await _ReturnService.UpdateOut(salesOut);
                    }


                    await myDbContext.SaveChangesAsync();

                    return Ok("添加成功");
                }
                else
                {
                    return BadRequest("添加失败！");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }
        private async Task<string> GetMaxCodeNumber()
        {
            // 从数据库中获取最大的仓库编码数字部分
            string maxCodeString = await myDbContext.pur_Sales_Return
                .Where(w => w.Return_code.StartsWith("CGTH"))
                .Select(w => w.Return_code.Substring(12))
                .OrderByDescending(code => code)
                .FirstOrDefaultAsync<string?>();

            // 如果数据库中没有记录或者记录的编码不符合预期格式，则返回 "0001"
            if (string.IsNullOrEmpty(maxCodeString))
            {
                return "01";
            }
            // 解析最大编码的数字部分
            int maxCodeNumber = int.Parse(maxCodeString);
            Console.WriteLine(maxCodeNumber);

            // 生成新的编码数字部分
            int newCodeNumber = maxCodeNumber + 1;

            // 如果新的编码数字部分超过了99，则重置为01
            if (newCodeNumber > 99)
            {
                newCodeNumber = 1;
            }
            return newCodeNumber.ToString();

        }
        // 生成新的仓库编码
        private string GenerateSaleCode(int codeNumber)
        {
            // 获取当前日期的字符串表示形式，格式为 "yyyyMMdd"
            string dateString = DateTime.Now.ToString("yyyyMMdd");

            // 将数字转换为两位字符串，并在前面补零
            string codeString = codeNumber.ToString("D2");

            // 返回完整的编码，包括前缀 "XSDD"、日期部分和数字部分
            return "CGTH" + dateString + codeString;
        }



        /// <summary>
        /// 采购退货审核
        /// </summary>
        /// <param name="Return_Id"></param>
        /// <returns></returns>
        [HttpPost("{Return_Id}")]
        public async Task<IActionResult> AuditSalesReturn(int Return_Id)
        {
            // 从数据库中获取销售订单及其关联的订单详情
            var salesReturn = await myDbContext.pur_Sales_Return
                .Include(so => so.pur_Sales_From) // 确保加载关联的订单详情
                .FirstOrDefaultAsync(so => so.Return_Id == Return_Id);

            // 如果销售订单不存在或已经被逻辑删除，则返回错误信息
            if (salesReturn == null || salesReturn.IsDeleted)
            {
                return NotFound("未找到对应的数据");
            }
            // 检查从表sal_Orders是否有数据
            if (!salesReturn.pur_Sales_From.Any() || salesReturn.pur_Sales_From.All(order => order.IsDeleted))

            {
                return BadRequest("从表没有数据，不能进行审核");
            }

            // 检查退货状态，如果为2，则不能进行审核
            if (salesReturn.Return_status == "2")
            {
                return BadRequest("该订单已经正在进行退货，不能进行审核");
            }

            try
            {
                // 审核销售订单
                salesReturn.AuditStatus = true;
                salesReturn.Return_status = "2";
                salesReturn.auditor = "Admin";
                salesReturn.auditTime = DateTime.UtcNow;

                // 同时更新关联的销售订单状态
                var salesOrder = await myDbContext.pur_Chase_Receipt
                    .FirstOrDefaultAsync(so => so.pr_number == salesReturn.ord_number);

                var salesOrder2 = await myDbContext.pur_Purchase_Order
                   .FirstOrDefaultAsync(so => so.ord_number == salesReturn.ord_number);
                if (salesOrder != null)
                {
                    salesOrder.out_Return_status = salesReturn.Return_status; // 更新销售入库状态
                }
                else if (salesOrder2 != null)
                {
                    salesOrder2.so_Return_status = salesReturn.Return_status; //更新销售订单状态 
                }


                if (salesReturn.so_out_status == '2')
                {
                    foreach (var returnItem in salesReturn.pur_Sales_From)
                    {
                        var invStorage = new inv_other_outbound
                        {
                            ioo_id = 0,
                            ioo_item_name = returnItem.fro_purname,
                            ioo_specification = salesReturn.Return_code,
                            ioo_item_attributes = "产品",
                            ioo_unit = "包",
                            ioo_quantity = (int)returnItem.Return_quantity,
                            ioo_warehouse = returnItem.w_Name,
                            ioo_operators = salesReturn.employee_name,
                            ioo_outbound_date = DateTime.Now,
                            ioo_type = "采购退货",
                            ioo_audit = false,
                            IsDeleted = false,
                            ioo_create_by = "Admin",
                            ioo_create_time = DateTime.Now,
                            ioo_update_by = "Admin",
                            ioo_update_time = DateTime.Now,
                        };
                        myDbContext.inv_other_outbound.Add(invStorage);
                    }
                }

                // 保存更改到数据库
                await myDbContext.SaveChangesAsync();

                return Ok("审核成功，已退货成功");
            }
            catch (DbUpdateException ex)
            {
                return StatusCode(500, "审核失败，数据库更新异常：" + ex.Message);
            }
        }


    }
}
